<template>
    <Dialog :app-dialog="appDialog">
        <div>
            <div class="tips-message">
                <div>1、以下为使用过该欢迎语的未开始或正在进行中的活动数据，仅支持此功能上线后的创建的数据</div>
                <div>2、勾选中的数据将更新为当前修改的最新欢迎语</div>
            </div>
            <ZwSearchForm :option="searchOption" @search="search" @reset="reset" />
            <ZwTable
                ref="tableRef"
                row-id-key="activity_id"
                :select-all-group="true"
                :option="tableOption"
                :row-key="getRowKey"
                :fetch-params="state.searchParams"
                :fetch-api="fetchApi()"
                @selection-change="onSelectionChange"
                @select-all="onSelectAll"
                @select-all-change="onSelectAllChange"
                @select-all-total="onSelectAllTotal">
            </ZwTable>
        </div>
    </Dialog>
    <Dialog :app-dialog="appDialog2">
        <div class="msg-content">
            您即将【批量更新欢迎语】<span class="msg_num">{{ selectTableTotal }}</span> 条数据，确认要执行此操作吗？
        </div>
    </Dialog>
</template>
<script setup lang="tsx">
import { ref, reactive, computed, watch, onMounted, nextTick } from 'vue';
import { deepCopy } from '@/utils/helper';
import { getWelcomeFriendModule, welcomeFriendList } from '@/api/channel/qwbase';
import { getCreateList } from '@/api/common';

import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import Dialog from '@/components/Dialog.vue';

const emit = defineEmits(['submit']);

const tableRef = ref<any>(null);
const cancelAllList = ref<any>([]);
const checkList = ref<any>([]);

const activityTypeList = ref<any>([]);

const selectTableTotal = ref<any>(null);

const submitHandel = () => {
    if (selectTableTotal.value) {
        appDialog2.visible = true;
    } else {
        emit('submit', 1, []);
        appDialog.visible = false;
    }
};

const cancelHandel = () => {
    reset();
    appDialog.visible = false;
};

const submitHandel2 = e => {
    const isSelectAll = tableRef.value.getIsSelectAll();
    const type = isSelectAll ? 2 : 1;
    let list = [];
    if (type == 2) {
        list = cancelAllList.value;
    } else {
        list = checkList.value;
    }
    emit('submit', type, list, true, e);
    appDialog2.visible = false;
    appDialog.visible = false;
};

const cancelHandel2 = () => {
    appDialog2.visible = false;
};

const appDialog = reactive<any>({
    visible: false,
    title: '更新欢迎语',
    width: '1000px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '确定'
});

const appDialog2 = reactive<any>({
    visible: false,
    title: '【批量更新欢迎语】',
    width: '500px',
    cancel: cancelHandel2,
    submit: submitHandel2,
    cancelText: '取消',
    submitText: '确定'
});

const getStatusClass = (val?: any) => {
    const list = [
        { className: 'status_grey', code: '1' },
        { className: 'status_blue', code: '2' }
    ];
    const info: any = list.find(el => el.code == val) || {};
    return info.className;
};

const searchOption = computed(() => {
    return [
        {
            label: '标题',
            name: 'activity_name',
            type: 'input',
            value: '',
            clearable: true,
            placeholder: '请输入标题'
        },
        {
            label: '应用模块',
            name: 'activity_type',
            type: 'select',
            value: '',
            clearable: true,
            placeholder: '请选择应用模块',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    resolve(activityTypeList.value);
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '创建人',
            name: 'created_uid',
            value: '',
            type: 'select',
            placeholder: '请选择员工',
            filterable: true,
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    getCreateList({}).then((res: any) => {
                        const targetArr = res.map((item: any) => {
                            item.name = `${item.name}  (${item.phone}) `;
                            return item;
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '创建时间',
            name: 'created_at',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        },
        {
            label: '是否修改',
            name: 'is_modify',
            type: 'select',
            value: '',
            clearable: true,
            placeholder: '请选择是否修改',
            optionList: [
                { value: '0', label: '全部' },
                { value: 2, label: '是' },
                { value: 1, label: '否' }
            ]
        }
    ];
});

const tableOption = [
    {
        type: 'selection',
        width: 55,
        fixed: 'left',
        reserveSelection: true
    },
    {
        prop: 'activity_name',
        label: '标题',
        width: 210,
        showOverflowTooltip: true
    },
    {
        prop: 'activity_type_name',
        label: '应用模块',
        width: 130,
        showOverflowTooltip: true
    },
    {
        prop: 'nickname',
        label: '活动状态',
        width: 120,
        render({ row, column, index }: any) {
            return <div className={`${getStatusClass(row.activity_status)} status`}>{row.activity_status_name}</div>;
        }
    },
    {
        prop: 'is_modify',
        label: '是否修改',
        width: 100,
        render({ row, column, index }: any) {
            return <div>{row.is_modify == 1 ? '否' : row.is_modify == 2 ? '是' : '--'}</div>;
        }
    },
    {
        prop: 'user_name',
        label: '创建人',
        width: 140
    },
    {
        prop: 'created_at',
        label: '创建时间',
        minWidth: 210
    }
];

const defaultParams = {
    welcome_friend_id: '',
    activity_name: '',
    activity_type: '0',
    created_uid: '',
    created_at: [],
    is_modify: '0'
};

const state = reactive({
    searchParams: deepCopy(defaultParams)
});

const getRowKey = (row: any) => {
    return row.activity_id;
};

const search = (data: any) => {
    const welcome_friend_id = state.searchParams.welcome_friend_id;
    tableRef.value.clearAllSelect();
    tableRef.value.getTable().clearSelection();
    state.searchParams = deepCopy({ ...defaultParams, ...data, welcome_friend_id });
};

const reset = () => {
    const welcome_friend_id = state.searchParams.welcome_friend_id;
    tableRef.value.clearAllSelect();
    tableRef.value.getTable().clearSelection();
    state.searchParams = deepCopy({ ...defaultParams, welcome_friend_id });
};

const fetchApi = () => {
    return welcomeFriendList;
};

const onSelectionChange = (selection: any) => {
    checkList.value = selection.map((v: any) => v.activity_id);
};

const onSelectAll = (selection: any) => {
    if (selection.constructor === Array) checkList.value = selection.map(v => v.activity_id);
};

const onSelectAllChange = (val: any) => {
    cancelAllList.value = val || [];
};

const onSelectAllTotal = (val: any) => {
    selectTableTotal.value = val;
};

const initModule = async () => {
    const res = await getWelcomeFriendModule();
    res.unshift({ id: '0', name: '全部' }) || [];
    activityTypeList.value = res;
};

watch(
    () => appDialog.visible,
    val => {
        nextTick(() => {
            val && tableRef.value.setIsAll();
        });
    }
);

onMounted(() => {
    initModule();
});

nextTick(() => {});

defineExpose({
    appDialog,
    state
});
</script>
<style lang="scss" scoped>
.tips-message {
    margin: 8px 0 16px;
    padding: 16px;
    line-height: 20px;
    font-size: 14px;
    color: #585858;
    background: #fffaf9;
    border-radius: 4px;
}

:deep(.status) {
    display: flex;
    align-items: center;

    &::before {
        display: inline-block;
        width: 8px;
        height: 8px;
        margin-right: 6px;
        content: '';
        border-radius: 4px;
        background: #d8d8d8;
    }
}

:deep(.status_grey::before) {
    background: #d8d8d8;
}

:deep(.status_blue::before) {
    background: #2fb6e4;
}

.msg-content {
    margin: 20px 0;
}
</style>
